package com.eclink.iot.tcpserver.websocket;

import com.alibaba.fastjson.JSONObject;
import com.eclink.iot.tcpserver.domain.business.DeviceWebsocketSession;
import com.eclink.iot.tcpserver.domain.request.WebsocketRequest;
import com.eclink.iot.tcpserver.entity.WelcomeMessage;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

@Slf4j
@Component
@ServerEndpoint("/rfid")
public class RFIDWebSocketServer {

    @OnOpen
    public void onOpen(Session session) {
        log.info("Connection opened: {}", session.getId());
        sessions.add(new DeviceWebsocketSession(session));
    }

    @OnMessage
    public void onMessage(Session session, String message) throws Exception {
        WebsocketRequest websocketRequest = JSONObject.parseObject(message, WebsocketRequest.class);
        if (websocketRequest.getCommand().equals("setUuid")) {
            // 设置Session，订阅所需监听的uuid
            log.info("Session {} 绑定uuid：{}", session.getId(), websocketRequest.getData());
            setUuid(session, websocketRequest.getData());
        }
        System.out.println("Received message: " + message);
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("Connection closed: " + session.getId());
        removeSession(session);
    }

    public DeviceWebsocketSession getSession(Session session) {
        for(DeviceWebsocketSession s : sessions) {
            if(s.getSession().getId().equals(session.getId())) {
                return s;
            }
        }
        return null;
    }

    public void setUuid(Session session, String uuid) {
        DeviceWebsocketSession deviceWebsocketSession = getSession(session);
        deviceWebsocketSession.setUuid(uuid);
    }

    public void removeSession(Session session) {
        DeviceWebsocketSession ss = getSession(session);
        if (ss != null) {
            sessions.remove(ss);
        }
    }

    public DeviceWebsocketSession getSessionsByUuid(String uuid) {
        for(DeviceWebsocketSession s : sessions) {
            if(uuid.equals(s.getUuid())) {
                return s;
            }
        }
        return null;

    }

    public static final Set<DeviceWebsocketSession> sessions = new HashSet<>();


}
